package nl.windgazer.arachne.services;

import org.apache.tapestry5.services.Cookies;

/**
 * This implementation is only intended as 'documentation by code' and can be used for non-secured sites without
 * much risk. However, if you wish to make use of any of the translatables I strongly urge you to override and
 * implement some form of actual security!!
 * 
 * @author mreuring
 *
 */
public class ArachnePrivilegesImpl implements ArachnePrivileges {

	final private static String SESSION_PID = "t5-arachne.privilegedID";
	final public static String SESSION_ROLES = "t5-arachne.privilegedRoles";
	final public static String ROLE_GUEST = "GUEST"; 
	final public static String ROLE_ADMIN = "ADMIN";
	private Cookies _cookies; 

	public ArachnePrivilegesImpl(Cookies cookies) {
		_cookies = cookies;
	}

	/**
	 * This implementation generates a relatively unique char-sequence in order to allow
	 * the automatically saves form-info for guests not to 'bleed' over into another
	 * users' session. Mostly this is only intended for basic testing / prototyping and
	 * I strongly encourage specific implementation overrides!!!
	 */
	public String getPrivilegedID() {
		String privilegedID = _cookies.readCookieValue(SESSION_PID);

		//Still null, so no request, or no cookie
		if (privilegedID == null) {
			privilegedID = Long.toString(Math.round(Math.random() * Long.MAX_VALUE), 16); //Terribly unsafe, but at least provides some measure of uniqueness
			_cookies.writeCookieValue(SESSION_PID, privilegedID);
		}

		return privilegedID;
	}

	/**
	 * This might return roles defined in the session / cookies of the user and if none are found
	 * it return the guest roles.
	 * This is extremely unsafe and only intended for testing purposes!
	 */
	public String[] getSecurityRoles() {
		final String rolesString = _cookies.readCookieValue(SESSION_ROLES);
		if (rolesString!=null) {
			return rolesString.split(", ?");
		}
		return new String[]{ROLE_GUEST};
	}

	public boolean hasRole(String role) {
		for (String r : getSecurityRoles()) {
			if (r.equals(role)) return true;
		}
		return false;
	}

	public static void setRole(String role, Cookies cookies) {
		final StringBuffer roles = new StringBuffer();
		final String rolesString = cookies.readCookieValue(SESSION_ROLES);

		if (rolesString!=null) {
			roles.append(rolesString);
		}

		if (roles.length() > 0) roles.append(", ");
		roles.append(role);
		
		cookies.removeCookieValue(SESSION_ROLES);
		cookies.writeCookieValue(SESSION_ROLES, roles.toString());
	}

	public static void logout(Cookies cookies) {
		cookies.removeCookieValue(SESSION_ROLES);
		cookies.removeCookieValue(SESSION_PID);
	}

}
